//
//  Utils.m
//  ssy
//
//  Created by 李志权 on 15/6/15.
//  Copyright (c) 2015年 深圳时时医科技有限公司. All rights reserved.
//

#import "Utils.h"
#include "sys/stat.h"//c语言计算文件大小
#import "sys/utsname.h"//获取手机型号
#import "JSONKit.h"
#import "NSString+DES.h"
#import "ImageCompress.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

/**左菜单*/
#import "MYUITabBarController.h"
#import "MYUINavigationController.h"
#import "PersonalDataViewController.h"
#import "DataStatisticsVC.h"
#import "MassageProgram.h"
#import "PopularActivitiesVC.h"
#import "MyWebViewVC.h"
#import "IMFacility.h"
#import "Feedback.h"
#import "MYAlertView.h"
//#import "lo"

@implementation Utils
 
/** AFNetworking网络POST请求*/

+ (NSURLSessionDataTask *)POSTMethod:(NSString *)URLString
                          parameters:(id)parameters
                           isRespone:(BOOL)isRespone
                             success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                             failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];//返回json(NSDictionary对象)

    NSLog(@"%@",parameters);
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    URLString  = [NSString stringWithFormat:@"%@%@",ServerPrefix,URLString];
    URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    UIView *HUD = [Utils getHUDView];
    
    NSURLSessionDataTask *DataTask = [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) { success(task, responseObject);}
        [HUD removeFromSuperview];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (success) { success(task, error);}
        [HUD removeFromSuperview];
    }];
    return DataTask;
    
}


/** AFNetworking网络GET HTTP请求*/
+ (NSURLSessionDataTask *)GETRequest:(NSString *)URLString
                           parameters:(id)parameters
                              success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                              failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
     manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];//返回json(NSDictionary对象)
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    URLString  = [NSString stringWithFormat:@"%@%@",ServerPrefix,URLString];
    URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    //加密
//    NSDictionary *dic=nil;
//    if (parameters) {
//        
//        NSString *str=[parameters JSONString];
//        str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        dic=@{
//              @"param":[str stringToDES]
//              };
//    }
//    
    // Get请求
    
    UIView *HUD = [Utils getHUDView];
    
    NSURLSessionDataTask *DataTask= [manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) { success(task, responseObject);}
        [HUD removeFromSuperview];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        if (failure) { failure(task, error);
            [HUD removeFromSuperview];
            [Utils alertMessage:KAlertMessage];
        }

    }];
  
    return DataTask;
}
/**系统post请求*/
+(void)systemPOSTMethod:(NSString *)URLString Parameters:(NSString *)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
{
    URLString = [NSString stringWithFormat:@"%@%@",ServerPrefix,URLString];
    NSURL *url = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    //第三步，创建异步请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET

    [request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];//设置body
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];//设置header
    
    //也可以使用异步block块
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue] //主线程
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                   if (data) {
                                       if (success) {
                                           success(nil,data);
                                       }
                                   }
                                   else
                                   {
                                       if (failure) { failure(nil,connectionError);}
                                   }
                                  
        }];
}
/**打印字典*/
+ (void)logDic:(NSDictionary *)dic
{
    NSString *tempStr1 = [[dic description] stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];
    NSLog(@"dic:%@",str);
}

/** json对象转NSString*/
+ (NSString*)JsonObjectConvertNSString:(id)jsonObject
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}



/** 将字典或者数组转化为JSON串*/
+ (NSData*)JsonToData:(id)theData
{
    /*
     将字典或者数组转化为NSData，再转NSString
     NSData *data = [Utils toJSONData:NSDictionary or NSArray];
     NSString *jsonString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     */

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }else{
        return nil;
    }
}



/** 将JSON串转化为字典或者数组*/
+ (id)JsonStringToArrayOrNSDictionary:(NSData*)jsonData
{
    /*
     将NSString转化为NSData，再转字典或者数组
     NSData *data = [jsonString dataUsingEncoding:NSASCIIStringEncoding];
     NSDictionary or NSArray = [Utils JsonStringToArrayOrNSDictionary:data];
     */
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        //解析错误
        return nil;
    }
    
}



/**
 @功能：解析网络json信息
 @参数：网络json信息字符串
 */
+ (id)parseJSON:(NSString*)strJSON
{
    id root;
    
    //使用系统的NSJSONSerialization
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
    {
        NSData *data = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
        root = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        //NSLog(@"NSJSONSerialization=%@", rootDic);
    }
    return root;
}



/** 自动提示框*/
+ (void)alertMessage:(NSString*)message
{
    [AutoFadeWithLabel labelWithString:message];
}

/** 判断UITextView CGSize*/
+ (CGSize)TakeTextViewSize:(UITextView*)txt
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
    //ios7.0以前使用的方法
    CGSize size = [txt.text sizeWithFont:txt.font
                                  constrainedToSize:CGSizeMake(txt.bounds.size.width, MAXFLOAT)
                                      lineBreakMode:NSLineBreakByWordWrapping];
    return size;
#else
    //ios7.0以后使用的方法
    NSDictionary *attribute = @{NSFontAttributeName:txt.font};
    CGSize size = [txt.text boundingRectWithSize:CGSizeMake(txt.bounds.size.width, MAXFLOAT)
                                                    options:NSStringDrawingUsesLineFragmentOrigin|
                   NSStringDrawingUsesFontLeading attributes:attribute
                                                    context:nil].size;
    return size;
#endif
}





/** 判断UIButton CGSize*/
+ (CGSize)TakeButtonSize:(UIButton*)btn
{
    #if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
        //ios7.0以前使用的方法
        CGSize size = [btn.titleLabel.text sizeWithFont:btn.titleLabel.font
                                      constrainedToSize:CGSizeMake(btn.bounds.size.width, MAXFLOAT)
                                          lineBreakMode:NSLineBreakByWordWrapping];
        return size;
    #else
        //ios7.0以后使用的方法
        NSDictionary *attribute = @{NSFontAttributeName:btn.titleLabel.font};
        CGSize size = [btn.titleLabel.text boundingRectWithSize:CGSizeMake(btn.bounds.size.width, MAXFLOAT)
                                                        options:NSStringDrawingUsesLineFragmentOrigin|
                       NSStringDrawingUsesFontLeading attributes:attribute
                                                        context:nil].size;
        return size;
    #endif
}





/** 判断UILable CGSize*/
+ (CGRect)TakeHeight:(UILabel*)label
{
    // 计算文本的高度
    NSDictionary *attribute = @{NSFontAttributeName:label.font};
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(label.bounds.size.width,MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  attributes:attribute context:nil].size;
    CGRect rect =label.frame;
    label.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width,size.height);
    return label.frame;

}
/** MD5加密*/
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (int)strlen(cStr), result);
    //    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}
/** MD5加密16大写*/
+ (NSString *)md516:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    str = [NSString stringWithFormat:
           @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
           result[0], result[1], result[2], result[3],
           result[4], result[5], result[6], result[7],
           result[8], result[9], result[10], result[11],
           result[12], result[13], result[14], result[15]
           ];
    
    str = [str substringWithRange:NSMakeRange(8, 16)];
    
    
    return str;
}
/**SHA1加密*/
+ (NSString*)sha1:(NSString *)str
{
    const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithBytes:cstr length:str.length];
    //使用对应的CC_SHA1,CC_SHA256,CC_SHA384,CC_SHA512的长度分别是20,32,48,64
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    //使用对应的CC_SHA256,CC_SHA384,CC_SHA512
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

/**AES加密*/
+ (NSString *)AES128okey:(NSString *)key iv:(NSString *)iv content:(NSString *)content
{
    
    
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    // IV
    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    
    size_t bufferSize = [contentData length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
 
   
    CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,  keyPtr, kCCKeySizeAES128,  ivPtr,  [contentData bytes], [contentData length],  buffer, bufferSize,  &numBytesEncrypted);
    
    if(cryptorStatus == kCCSuccess){
        NSLog(@"Success");
 
        return [[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
    }else{
        NSLog(@"Error");
    }
    
    free(buffer);
    return nil;
}
/** 判断输入手机号码的合法性*/
+ (BOOL)isValidatePhone:(NSString*)phone
{
    if (phone != nil && [phone length]!= 0)
    {
        if (![Utils ValidatePhone:phone])
        {
            [Utils alertMessage:@"手机号码不正确"];
            return NO;
        }
        else return YES;
    }
    [Utils alertMessage:@"请输入手机号码"];
    return NO;
}
/**判断银行卡是否合法*/
+ (BOOL)checkCardNo:(NSString*)cardNo{
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}


/** 判断输入验证码的时间是否过期*/
+ (BOOL)isValidateTimeOut:(NSString*)vdate
{
    NSDate *dateNow = [NSDate date];
    long timeSp = (long)[dateNow timeIntervalSince1970];
    
    long inputSp = (long)[vdate longLongValue];
    int timeSpan = (int)timeSp - (int)inputSp;
    if (timeSpan < 120)
        return YES;
    else
    {
        [Utils alertMessage:@"验证码超时"];
        return NO;
    }
}



/** 判断输入验证码的合法性*/
+ (BOOL)isValidateCode:(NSString*)code usercode:(NSString*)usercode
{
    if (code != nil && [code length] >= 6 && usercode != nil && [usercode length] >= 6)
    {
        if ([code isEqual:usercode])
            return YES;
        else
        {
            [Utils alertMessage:@"验证码错误"];
            return NO;
        }
    }
    else
    {
        [Utils alertMessage:@"请输入6位验证码"];
        return NO;
    }
}





/** 判断输入密码的合法性*/
+ (BOOL)isValidateTempPassword:(NSString*)TempPassword
{
    if (TempPassword != nil && [TempPassword length] != 0)
    {
        if ([TempPassword length] < 6 ||[TempPassword length] >12)
        {
            [Utils alertMessage:@"用户密码不能少于6位数或大于12位数"];
            return NO;
        }
        else return YES;
    }
    [Utils alertMessage:@"请输入您的密码"];
    return NO;
}





/** 判断两次输入密码是否相同*/
+ (BOOL)isValidateConfirmPassword:(NSString*)TempPassword ConfirmPassword:(NSString*)ConfirmPassword
{
    if ([TempPassword length] !=0 && (ConfirmPassword != nil && [ConfirmPassword length] != 0))
    {
        if (![TempPassword isEqualToString:ConfirmPassword])
        {
            [Utils alertMessage:@"两次输入的密码不一致"];
            return NO;
        }
        else return YES;
    }
    [Utils alertMessage:@"两次输入的密码不一致"];
    return NO;
}





/** 利用正则表达式验证手机号码的合法性*/
+ (BOOL)ValidatePhone:(NSString *)phone
{
    NSString *phoneRegex = @"^[1][3-8]+\\d{9}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

/** 利用正则表达式验证邮箱的合法性*/
+ (BOOL)ValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/** 
 功能：画一条线
 参数：“top”：0，0，Width，0.5；“middle”：20，0，Width-20, 0.5；“bottom”：0, 49.5, Width, 0.5
 */
+ (UIView*)drawLine:(NSString*)type  height:(CGFloat)height
{
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = GrayTooLight;
    
    if ([type isEqualToString:@"top"])
    {
        line.frame = CGRectMake(0, height, Width, 0.5);
    }
    else if ([type isEqualToString:@"middle"])
    {
        line.frame = CGRectMake(10, height-0.5, Width-20, 0.5);
    }
    else  if ([type isEqualToString:@"bottom"])
    {
        line.frame = CGRectMake(0, height-0.5, Width, 0.5);
    }
    return line;
}



/** NSString转NSDate*/
+ (NSDate*)NSStringConvertNSDate:(NSString*)strDate format:(NSString*)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:format];
    NSDate *date = [formatter dateFromString:strDate];
    return date;
}


/** NSDate转NSString*/
+ (NSString*)NSDateConvertNSString:(NSDate*)date format:(NSString*)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:format];
    NSString *strDate = [formatter stringFromDate:date];
    return strDate;
}


/** NSDate转NSString*/
+ (NSString*)NSDateConvertNSString_Index:(NSString*)dateString format:(NSString*)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    [dateFormatter setDateFormat:format];
    NSString *dataStr = [dateFormatter stringFromDate:date];
    return dataStr;
}




/** 把GMT日期转换成UTC*/
+ (NSDate*)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}




/** 返回多久之前的时间*/
+ (NSString*)returnUploadTime:(NSString *)timeStr
{
    //Thu June 25 16:36:45 +0800 2015
    
    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    [date setDateFormat:@"E MMM d HH:mm:SS Z y"];
    NSDate *d = [date dateFromString:timeStr];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString= @"";
    
    NSTimeInterval cha = now - late;
    
    //如果小于一小时
    if (cha / 3600 < 1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        if ([timeString isEqualToString:@"0"])
            timeString = @"1";
        timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
    }
    //如果大于1小时，并且小于24小时
    if (cha / 3600 > 1 && cha / 86400 < 1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
        
        //获取昨天的日期
        NSDateFormatter *yesterdayFormatter = [[NSDateFormatter alloc] init];
        [yesterdayFormatter setDateFormat:@"dd"];
        NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)];
        [yesterdayFormatter stringFromDate:yesterday];
        NSString *strYesterday = [yesterdayFormatter stringFromDate:yesterday];
        
        //获取传进参数的日期和时间
        NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"dd HH:mm"];
        NSString *hour = [dateformatter stringFromDate:d];
        
        //比较参数是否大于昨天的最后一秒，小于则显示昨天，大于则显示今天
        if ([hour compare:[NSString stringWithFormat:@"%@ 23:59:59", strYesterday]] <= 0)
        {
            [dateformatter setDateFormat:@"HH:mm"];
            timeString = [NSString stringWithFormat:@"昨天 %@", [dateformatter stringFromDate:d]];
        }
        else
        {
            [dateformatter setDateFormat:@"HH:mm"];
            timeString = [NSString stringWithFormat:@"今天 %@", [dateformatter stringFromDate:d]];
        }
    }
    if (cha/86400 > 1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        
        if ([timeString intValue] <= 3)
            timeString=[NSString stringWithFormat:@"%@天前", timeString];
        else
        {
            NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm"];
            timeString = [NSString stringWithFormat:@"%@",[dateformatter stringFromDate:d]];
        }
    }
    return timeString;
}
//判断日期是今天，昨天还是明天   
+(NSString *)compareDate:(NSString *)time{
    
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *fromdate=[format dateFromString:time];
    
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *date = [fromdate  dateByAddingTimeInterval: frominterval];
    
    NSTimeInterval secondsPerDay = 24*60*60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow,*yesterday,*afterDay;
    tomorrow = [today dateByAddingTimeInterval:secondsPerDay];
    afterDay = [today dateByAddingTimeInterval:secondsPerDay*2];
    yesterday = [today dateByAddingTimeInterval:-secondsPerDay];
    NSString *todayString = [[today description]substringToIndex:10];
    NSString *yesterdayString = [[yesterday description]substringToIndex:10];
    NSString *tomorrowString = [[tomorrow description]substringToIndex:10];
    NSString *afterDayString = [[afterDay description]substringToIndex:10];
    NSString *dateString = [[date description]substringToIndex:10];
    if ([dateString isEqualToString:todayString]) {
        return @"今天";
    }else if ([dateString isEqualToString:yesterdayString])
    {
        return @"昨天";
    }
    else if ([dateString isEqualToString:tomorrowString])
    {
        return @"明天";
    }
    else if ([dateString isEqualToString:afterDayString])
    {
        return @"后天";
    }
    else
    {
        return dateString;
    }
}

+ (NSString *)compareCurrentTime:(NSDate*)compareDate
{
    //格式[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
    NSTimeInterval timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if ((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分前",temp];
    }
    else if ((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小前",temp];
    }
    else if ((temp = temp/24) <10){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    else
    {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"E MMM d HH:mm:SS Z y"];
//        NSString *timeStr = [dateFormatter stringFromDate:compareDate];
//        
//        NSDateFormatter *date = [[NSDateFormatter alloc] init];
//        [date setDateFormat:@"E MMM d HH:mm:SS Z y"];
//        NSDate *d = [date dateFromString:timeStr];
        
        NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"MM-dd HH:mm"];
        result = [NSString stringWithFormat:@"%@",[dateformatter stringFromDate:compareDate]];
    }
//    else if ((temp = temp/24) <30){
//        result = [NSString stringWithFormat:@"%ld天前",temp];
//    }
//    else if((temp = temp/30) <12){
//        result = [NSString stringWithFormat:@"%ld个月前",temp];
//    }
//    else{
//        temp = temp/12;
//        result = [NSString stringWithFormat:@"%ld年前",temp];
//    }
    return result;
}
//获取时间戳
+(NSString *)getTime
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
   return  [NSString stringWithFormat:@"%0.0f",a];//转为字符型
}


+ (NSString*)SecondsToTime:(long)timeInterval
{
    NSString *result = @"";
    long temp = 0;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"00:%.2ld", timeInterval];
    }
    else if ((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%.2ld:%.2ld", temp, timeInterval%60];
    }
    return result;
}





/** 是否显示网络加载菊花*/
+ (void)NetworkActivityIndicatorVisible:(BOOL)isShowOrHide
{
        UIApplication *app = [UIApplication sharedApplication];
        app.networkActivityIndicatorVisible = isShowOrHide;
}




/**
 因为要在UITableViewCell里面的UIView模块里面
 调用self.navigationcontroller pushviewcontroller推入一个新的ViewController，
 需要获取其上层的UIViewController
 */
+ (UIViewController*)GetSuperController:(UIView*)view
{
    id object = [view nextResponder];
    while (![object isKindOfClass:[UIViewController class]] && object != nil)
        object = [object nextResponder];
    
    UIViewController *vc = (UIViewController*)object;
    return vc;
}

/**获取首个viewcontroller*/
+(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

/** 图片压缩*/
+ (UIImage*)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}




/** 遍历文件夹获得文件夹大小，返回多少M*/
+ (float)folderSizeAtPath:(NSString*)folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}




/** c语言获取单个文件大小,返回kb*/
+ (long long)fileSizeAtPath:(NSString*)filePath
{
    struct stat st;
    if(lstat([filePath cStringUsingEncoding:NSUTF8StringEncoding], &st) == 0)
    {
        return st.st_size;
    }
    return 0;
}




/** OC获取单个文件大小,返回kb*/
+ (float)fileNSSizeAtPath:(NSString*)filePath
{
    return [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize] / 1024.0;
}




/** 过滤html标签*/
+ (NSString*)HTMLFilter:(NSString*)description
{
    NSScanner *theScanner;
    NSString *text = nil;
    
    theScanner = [NSScanner scannerWithString:description];
    
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        description = [description stringByReplacingOccurrencesOfString:
                       [NSString stringWithFormat:@"%@>", text]
                                                             withString:@""];
    }
    
    description = [description stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&lt" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&gt;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&amp;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&cent;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&pound;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&yen;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&euro;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&sect;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&copy;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&reg;" withString:@""];
    description = [description stringByReplacingOccurrencesOfString:@"&trade;" withString:@""];
    
    return description;
}



/**
 *  获取网络当前时间
 */
+ (NSDate *)getInternetDate
{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // 实例化NSMutableURLRequest，并进行参数配置
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    //处理返回的数据
    //NSString *strReturn = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"response is %@",response);
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    return netDate;
}
/** 计算文本宽度*/
+ (CGRect)TakeWidth:(UILabel *)label
{
    // 计算文本的宽度
    NSDictionary *attribute = @{NSFontAttributeName:label.font};
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, label.bounds.size.height) options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  attributes:attribute context:nil].size;
    CGRect rect =label.frame;
    label.frame = CGRectMake(rect.origin.x, rect.origin.y, size.width, rect.size.height);
    return label.frame;
}

/** 获取手机型号*/
+ (NSString*)getModel
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    //iPod
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    //iPad
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2 (32nm)";
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad mini (GSM)";
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad mini (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3(WiFi)";
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3(CDMA)";
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3(4G)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4 (4G)";
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad5,1"])      return @"iPad mini 4";
    if ([deviceString isEqualToString:@"iPad5,2"])      return @"iPad mini 4";
    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad6,7"])      return @"iPad Pro";
    if ([deviceString isEqualToString:@"iPad6,8"])      return @"iPad Pro";
    
    if ([deviceString isEqualToString:@"iPad4,4"]
        ||[deviceString isEqualToString:@"iPad4,5"]
        ||[deviceString isEqualToString:@"iPad4,6"])      return @"iPad mini 2";
    
    if ([deviceString isEqualToString:@"iPad4,7"]
        ||[deviceString isEqualToString:@"iPad4,8"]
        ||[deviceString isEqualToString:@"iPad4,9"])      return @"iPad mini 3";
    
    if ([deviceString isEqualToString:@"i386"])         return @"iPhone Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"iPhone Simulator";
    
    return deviceString;
}
/**导航栏返回按钮*/
+ (void)navigationBarReturn:(UIViewController *)VC color:(UIColor *)color font:(UIFont *)font foregroundColor:(UIColor *)foregroundColor 
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    [VC.navigationController.navigationBar setBackgroundImage: theImage forBarMetrics:UIBarMetricsDefault];
    VC.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
    [VC.navigationController.navigationBar setTitleTextAttributes:  @{NSFontAttributeName:font,  NSForegroundColorAttributeName:foregroundColor}];
    
}
/**判断对象是否为null，返回字符对象*/
+(NSString *)judgeObjectString:(id)str
{
   str = [NSString stringWithFormat:@"%@",str];
    if ([str isEqualToString:@"<null>"] ||[str isEqualToString:@"(null)"]||[str isEqualToString:@"null"]) {
        str = @"";
    }
    return str;
}


/**修剪View角边*/
+ (void)shear:(UIView *)view
{
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = 3;
    view.layer.borderWidth =1;
    view.layer.borderColor = GrayTooLight.CGColor;
}
/**分段按钮*/
+(UISegmentedControl*)getUISegmentedArray:(NSArray *)array
{
    //分段控件 UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:array];
    segmentedControl.frame = CGRectMake(77/3, 10,Width-77/3-77/3, 40);//设置frame
    segmentedControl.momentary = NO;//设置点选状态,默认为NO,如果为YES,会立即消失被选中的状态(蓝色)
    segmentedControl.backgroundColor = [UIColor whiteColor];
    segmentedControl.tintColor = GreenColor;//设置分段控件整体颜色
    segmentedControl.selectedSegmentIndex = 0;//初始化被选中的分段
    [segmentedControl setShearRound:segmentedControl.highly/2 masksToBounds:YES borderWidth:2 borderColor:GreenColor];
    return segmentedControl;
    
}
/**自适应键盘高度
 参数贴在控制器上的View
 控制器
 */
+ (void)startAdaptiveKeyboardInputView:(UIView *)view topView:(UIView *)topView
{
    CGRect frame = view.frame;
    int offset = frame.origin.y + 32 - (topView.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        topView.frame = CGRectMake(0.0f, -offset,topView.frame.size.width, topView.frame.size.height);
    
    [UIView commitAnimations];
}
/**输入结束隐藏键盘参数控制器**/
+(void)inputEndOfHiddenKeyboardTopView:(UIView *)topView
{
    topView.frame =CGRectMake(0, 0, topView.frame.size.width, topView.frame.size.height);
}

/**HUD请等待*/
+(UIView *)getHUDView
{
    UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    UIView *aView = [[UIView alloc]initWithFrame:window.bounds];
    aView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [window addSubview:aView];
    UIView *HUD = [[HUD_SingleCase HUDALLOW] HUDDialogUntil:@"请等待"];
    [aView addSubview:HUD];
    return aView;
}
//照片获取本地路径转换
+ (NSString *)getImagePath:(UIImage *)Image {
    NSString *filePath = nil;
    NSData *data = [ImageCompress imageData:Image];
//    Image = [ImageCompress scaleToSize:Image size:CGSizeMake(960, 1280)];
//    if (UIImagePNGRepresentation(Image) == nil) {
//        data = UIImageJPEGRepresentation(Image, 1.0);
//    } else {
//        data = UIImagePNGRepresentation(Image);
//    }
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [[NSString alloc] initWithFormat:@"/theFirstImage.png"];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}

/** 选中后的颜色变化 */
+ (void)showClickedColor:(UIView *)clickedView
{
    clickedView.backgroundColor = MAINBGCOLOR;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        clickedView.backgroundColor = [UIColor whiteColor];
    });
}
/**结束刷新状态*/
+(void)endRefreshing:(UITableView *)tableView
{
    // 刷新表格
    [tableView reloadData];
    [tableView.mj_footer endRefreshing];
    // 拿到当前的下拉刷新控件，结束刷新状态
    [tableView.mj_header endRefreshing];
}
/**展示没数据*/
+(UILabel*)showNoData:(UIView *)superView
{
    UILabel *showNodata = [[UILabel alloc]initWithFrame:CGRectMake(0, superView.highly/2-20, Width, 40)];
    showNodata.text = @"没有数据";
    showNodata.textColor = MAINBLUEGrayDark;
    showNodata.font = fontSizeMaxMax;
    showNodata.textAlignment = NSTextAlignmentCenter;
    showNodata.hidden = YES;
    [superView addSubview:showNodata];
    return showNodata;
}


/**获取UIStoryboardVC*/
+(UIViewController *)instantiateVCWithIdentifier:(NSString *)identifier
{
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    return [main instantiateViewControllerWithIdentifier:identifier];
}
/**设置导航栏*/
+(UIView *)setnavigationViewLeftBtn:(UIButton *)leftBtn rightBut:(UIButton *)rightBut title:(NSString *)tile superView:(UIView *)superView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width, 64)];
    view.backgroundColor = [UIColor whiteColor];
    [superView addSubview:view];
    
    CGFloat rightButWidth = 0 ;
    if (rightBut) {
        rightButWidth = rightBut.width+10;
        [view addSubview:rightBut];
    }
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(leftBtn.XWidth, 20, Width-leftBtn.XWidth-rightButWidth, 44)];
    titleLabel.font = fontSizeIndexBTNTitie;
    titleLabel.textColor = MAINBLUELight;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = tile;
    [view addSubview:titleLabel];
    [view addSubview:leftBtn];
    
    return view;
    
}
/**生成XML*/
+(NSString *)XMLStringFromDictionary:(NSDictionary *)dictionary keys:(NSArray *)keys
{
    NSMutableString *XML = [NSMutableString string];
    [XML appendFormat:@"<%@>",[[dictionary allKeys] lastObject]];
    NSDictionary *dic = dictionary[[[dictionary allKeys]lastObject]];
    for (NSString *key in keys) {
        [XML appendFormat:@"<%@>%@</%@>",key,dic[key],key];
    }
    [XML appendFormat:@"</%@>",[[dictionary allKeys] lastObject]];
    return XML;
}
/**左菜单点击*/
+ (void)leftMenuClickIndex:(NSString *)vType
{
    MYUITabBarController *TB = (MYUITabBarController *)[Utils getCurrentVC];
    MYUINavigationController *NC= TB.selectedViewController;
    UIViewController *VC = NC.visibleViewController;
    UIViewController *SUBVC;
    switch (vType.intValue) {
        case 0:
            SUBVC = [[PersonalDataViewController alloc]init];
            break;
        case 1:
            SUBVC  = [[DataStatisticsVC alloc]init];
            break;
        case 2:
            SUBVC = [[MassageProgram alloc]init];
            break;
        case 3:
            SUBVC = [[PopularActivitiesVC alloc]init];
            break;
        case 4:
        {
            [Utils systemPOSTMethod:@"user/getOfficialMarket" Parameters:@"" success:^(NSURLSessionDataTask *task, id responseObject) {
                NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSDictionary *jsonDic = [Utils parseJSON:str];
                MyWebViewVC *VC= [[MyWebViewVC alloc]initWithUrl:jsonDic[@"url"]];
                VC.hidesBottomBarWhenPushed = YES;
                [VC.navigationController pushViewController:VC animated:YES];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            return;
        }
        case 5:
        {
            [Utils systemPOSTMethod:@"user/getOfficialJianuo" Parameters:@"" success:^(NSURLSessionDataTask *task, id responseObject) {
                NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSDictionary *jsonDic = [Utils parseJSON:str];
                MyWebViewVC *VC= [[MyWebViewVC alloc]initWithUrl:jsonDic[@"url"]];
                VC.hidesBottomBarWhenPushed = YES;
                [VC.navigationController pushViewController:VC animated:YES];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            return;
        }
        case 7:
        {
            SUBVC = [[IMFacility alloc]init];
            break;
        }
        case 8:
        {
            MYAlertView *alertView = [[[NSBundle mainBundle]loadNibNamed:@"MYAlertView" owner:self options:nil] lastObject];
            alertView.theTitle.text = @"清理缓存";
            alertView.alertContent.text  = @"确定清理缓存?";
            [alertView.btnTitle setTitle:@"确定" forState:UIControlStateNormal];
            __weak MYAlertView *weakAlertView = alertView;
            
            alertView.btnTitleBtnClick = ^(){
                [[SDImageCache sharedImageCache] clearDisk];
                weakAlertView.alertContent.text = @"缓存已清理";
                weakAlertView.isClosed = YES;
            };
            break;
        }
        case 9:
        {
            SUBVC = [[Feedback alloc]init];
            break;
        }
        default:
            break;
    }
    SUBVC.hidesBottomBarWhenPushed = YES;
    [VC.navigationController pushViewController:SUBVC animated:YES];
}
@end
